/*************************************************************
 * File: ParameterResource.java
 * Copyright (c) 2012
 * Author: Huang Shaobin
 * Email: Shaobin.Software@gmail.com Shaobin_Software@163.com 
 * Date: Mar 8, 2013
 * Description: 
 ************************************************************/

package snow.biz.system.web.rest;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.restlet.data.Form;

import snow.biz.system.model.Parameter;
import snow.biz.system.model.User;
import snow.biz.system.service.IParameterService;
import snow.core.enums.Status;
import snow.core.exceptions.BusinessException;
import snow.core.persistence.AndedConditions;
import snow.core.persistence.BinaryOperator;
import snow.core.persistence.Condition;
import snow.core.persistence.Conditions;
import snow.core.persistence.Order;
import snow.core.security.Operator;
import snow.core.security.annotations.Operation;
import snow.core.security.annotations.Resource;
import snow.core.web.rest.ResourceSupport;

/**
 * 系统配置参数相关的REST服务
 * 
 * @author Shaobin.Software@gmail.com Shaobin_Software@163.com
 * @version 1.0
 */
@Path("/system/parameters")
@Resource(uri = "/parameters")
public class ParameterResource extends ResourceSupport {

	private IParameterService parameterService;
	
	public static void main(String[] args) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		map.put("/system/menus", String.valueOf(Operator.CREATE.getValue()));
		JSONObject json = new JSONObject(map);
		System.out.println(json.toString());
	}

	@POST
	@Produces(MediaType.APPLICATION_JSON)
	@Operation(name = "添加配置参数", type = Operator.CREATE)
	public Object addParameter() throws BusinessException {
		final Form postForm = super.getPostAsForm();
		final String name = postForm.getFirstValue("name");
		final String type = postForm.getFirstValue("type");
		final String value = postForm.getFirstValue("value");
		final String comment = postForm.getFirstValue("comment");
		final Status status = Status.toStatusFrom(NumberUtils.toInt(postForm.getFirstValue("status"), 1));
		if (log.isDebugEnabled()) {
			log.debug("参数名称为：" + name);
			log.debug("参数类型为：" + type);
			log.debug("参数值为：" + value);
			log.debug("参数描述为：" + comment);
		}
		final User currentUser = parameterService.getCurrentUser();
		parameterService.createParameterFrom(new Parameter(currentUser, status, name, type, value, comment));
//		try {
//			
//		} catch (BusinessException e) {
//			return getResultFrom(false, e.getCode(), e.getMessage());
//		} catch (Exception e) {
//			log.error(e.getMessage(), e);
//			return getResultFrom(false, "200000", "failure.unknown.business.exception");
//		}
		return getSuccessResult();
	}

	@DELETE
	@Path("/{id:\\d+}")
	@Resource(uri = "/{id:\\d+}")
	@Produces(MediaType.APPLICATION_JSON)
	@Operation(name = "删除配置参数", type = Operator.REMOVE)
	public Object delParameter(@PathParam("id")
	Integer id) {
		return getSuccessResult();
	}

	@DELETE
	@Produces(MediaType.APPLICATION_JSON)
	@Operation(name = "批量删除配置参数", type = Operator.REMOVE)
	public Object delParameters() {
		final Form queryForm = super.getQueryAsForm();
		final String ids = queryForm.getFirstValue("ids");
		if (log.isDebugEnabled()) {
			log.debug("本次需要删除的参数ID值为：" + ids);
		}
		final String[] paramIdArr = StringUtils.split(ids, ',');
		if (!ArrayUtils.isEmpty(paramIdArr)) {
			for (String paramIdStr : paramIdArr) {
				final int id = NumberUtils.toInt(paramIdStr);
				try {
					final Parameter parameter = id > 0 ? null : parameterService.searchParameterFrom(Integer.valueOf(id));
					parameter.setStatus(Status.FAILURE);
					parameterService.removeParameterFrom(parameter);
				} catch (BusinessException e) {
					
				}
			}
		}
		return getSuccessResult();
	}

	public IParameterService getParameterService() {
		return this.parameterService;
	}

	@GET
	@Produces(MediaType.APPLICATION_JSON)
	@Operation(name = "显示配置参数列表", type = Operator.SEARCH)
	public Object listParameters() throws BusinessException {
		final Form queryForm = super.getQueryAsForm();
		final String name = queryForm.getFirstValue("name");
		final String type = queryForm.getFirstValue("type");
		final String value = queryForm.getFirstValue("value");
		final String comment = queryForm.getFirstValue("comment");
		final String status = queryForm.getFirstValue("status");
		final int start = NumberUtils.toInt(queryForm.getFirstValue("start"), -1);
		final int limit = NumberUtils.toInt(queryForm.getFirstValue("limit"), -1);
		if (log.isDebugEnabled()) {
			log.debug("字段[name]的查询参数为：" + name);
			log.debug("字段[type]的查询参数为：" + type);
			log.debug("字段[value]的查询参数为：" + value);
			log.debug("字段[comment]的查询参数为：" + comment);
			log.debug("字段[status]的查询参数为：" + status);
			log.debug("分页查询参数为：[start]->" + start + "；[limit]->" + limit);
		}
		final Conditions conditions = new AndedConditions();
		if (StringUtils.isNotBlank(name)) {
			conditions.addCondition(new Condition("name", BinaryOperator.LIKE, "%" + StringUtils.trimToEmpty(name) + "%"));
		}
		if (StringUtils.isNotBlank(type)) {
			conditions.addCondition(new Condition("type", BinaryOperator.LIKE, "%" + StringUtils.trimToEmpty(type) + "%"));
		}
		if (StringUtils.isNotBlank(value)) {
			conditions.addCondition(new Condition("value", BinaryOperator.LIKE, "%" + StringUtils.trimToEmpty(value) + "%"));
		}
		if (StringUtils.isNotBlank(comment)) {
			conditions.addCondition(new Condition("comment", BinaryOperator.LIKE, "%" + StringUtils.trimToEmpty(comment) + "%"));
		}
		if (!"all".equalsIgnoreCase(status)) { // 显示全部
			if ("failure".equalsIgnoreCase(status) || NumberUtils.toInt(status, -1) == 0) {
				conditions.addCondition(new Condition("status", BinaryOperator.EQ, Status.FAILURE));
			} else {
				conditions.addCondition(new Condition("status", BinaryOperator.EQ, Status.SUCCESS));
			}
		}
		try {
			return getParameterService().searchParametersForPagingFrom(conditions, Arrays.asList(new Order[] { Order.desc("createTime") }), start, limit);
		} catch (BusinessException e) {
			return getResultFrom(false, e.getCode(), e.getMessage());
		}
	}

	public void setParameterService(IParameterService parameterService) {
		this.parameterService = parameterService;
	}

	@GET
	@Path("/{id:\\d+}")
	@Produces(MediaType.APPLICATION_JSON)
	@Resource(uri = "/{id:\\d+}")
	@Operation(name = "显示配置参数明细", type = Operator.SEARCH)
	public Object showParameter(@PathParam("id")
	Integer id) {
		return null;
	}
}
